package org.watson.androidwebservice;

import java.io.IOException;
import java.io.StringReader;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.watson.bean.Phone;

import com.google.gson.Gson;
import com.google.gson.JsonObject;

import android.os.Bundle;
import android.os.StrictMode;
import android.app.Activity;
import android.util.Log;
import android.view.View;
import android.widget.EditText;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()  
        .detectDiskReads()  
        .detectDiskWrites()  
        .detectNetwork()   // or .detectAll() for all detectable problems  
        .penaltyLog()  
        .build());  
		StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()  
        .detectLeakedSqlLiteObjects()  
        .detectLeakedClosableObjects()  
        .penaltyLog()  
        .penaltyDeath()  
        .build());
    }
    
    public void sayHello(View view) {
    	EditText editText = (EditText) findViewById(R.id.editText1);
    	String name = editText.getText().toString();
    	callSayHello(name);
    }
    
    public void callSayHello(String name) {
    	String nameSpace = "http://Hacker.Watson.com/";  
        String methodName = "getInfo";  
        String endPoint = "http://10.0.2.2:8080/AndroidServer/DataServiceImplService";  
        String soapAction = "http://Hacker.Watson.com/getInfo";  
  
        SoapObject requestSoap = new SoapObject(nameSpace, methodName);  
  
        requestSoap.addProperty("arg0", name);  
  
        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);  
  
        //envelope.dotNet = true;  
        envelope.setOutputSoapObject(requestSoap);  
  
        HttpTransportSE transport = new HttpTransportSE(endPoint);  
        try {
            transport.call(soapAction, envelope);  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
  
        SoapObject object = (SoapObject) envelope.bodyIn;  
        String jsonData = object.getProperty(0).toString();
        Log.i("Json", jsonData);
        
        try {
        JSONObject xobject = new JSONObject(jsonData);
		JSONArray jsonArray = new JSONArray(xobject.getString("exchangeData"));
		String a0 = jsonArray.get(0).toString();
		Gson gson = new Gson();
		Phone phone = gson.fromJson(a0, Phone.class);
		Log.i("phone", phone.getModel());
		Log.i("a0", a0);
        Log.i("json", xobject.getString("exchangeData"));
		} catch (JSONException e) {
			e.printStackTrace();
		}
    }
}
